/**
 * OKR Mock API 接口
 * 模拟后端 API 接口，提供本地数据操作
 */

import type {
  OKRNode,
  KeyResult,
  CreateOKRNodeRequest,
  UpdateKeyResultRequest,
  OKRApiResponse
} from '../types/okr';
import { OKRNodeType, OKRStatus } from '../types/okr';

// 模拟网络延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// 生成唯一ID
const generateId = () => Date.now().toString(36) + Math.random().toString(36).substr(2);




/**
 * 生成组织架构式 OKR 树数据
 * 1个部门 → 3个团队 → 每个团队2个小组 → 每个小组3-5个人
 */
function generateOrganizationalOKRTree(quarter = '2024Q4'): { nodes: Record<string, OKRNode>; keyResults: Record<string, KeyResult[]> } {
  const nodes: Record<string, OKRNode> = {};
  const keyResults: Record<string, KeyResult[]> = {};
  let counter = 0;

  /**
   * 生成关键结果
   */
  const generateKeyResults = (nodeId: string, count: number = 2): KeyResult[] => {
    const results: KeyResult[] = [];
    const titles = [
      '营收增长', '客户满意度', '市场份额', '产品质量', '团队效率',
      '成本控制', '技术创新', '用户留存', '项目交付', '人才培养'
    ];

    for (let i = 0; i < count; i++) {
      const progress = Math.floor(Math.random() * 100);
      const title = titles[Math.floor(Math.random() * titles.length)];
      results.push({
        id: `kr-${nodeId}-${i + 1}`,
        title: `${title}目标`,
        description: `${nodeId} 的 ${title} 关键结果描述`,
        targetValue: 100,
        currentValue: progress,
        unit: Math.random() > 0.5 ? '%' : '个',
        progress,
        status: progress >= 100 ? OKRStatus.COMPLETED :
          progress >= 75 ? OKRStatus.IN_PROGRESS : OKRStatus.NOT_STARTED,
        deadline: '2024-12-31',
        createdAt: '2024-01-01',
        updatedAt: '2024-09-25'
      });
    }
    return results;
  };

  // 1. 创建部门目标
  const deptId = 'DEPT-001';
  const deptKeyResults = generateKeyResults(deptId, 3);
  keyResults[deptId] = deptKeyResults;

  const deptProgress = Math.round(deptKeyResults.reduce((sum, kr) => sum + kr.progress, 0) / deptKeyResults.length);

  nodes[deptId] = {
    id: deptId,
    title: '技术部门年度目标',
    description: '推动公司数字化转型，提升技术竞争力，实现业务增长目标',
    type: OKRNodeType.DEPARTMENT,
    parentId: undefined,
    children: [],
    keyResults: deptKeyResults,
    progress: deptProgress,
    status: deptProgress >= 100 ? OKRStatus.COMPLETED :
      deptProgress >= 75 ? OKRStatus.IN_PROGRESS : OKRStatus.NOT_STARTED,
    owner: {
      id: 'user-dept-001',
      name: '张技术总监',
      avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=dept001`,
      department: '技术部'
    },
    quarter,
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    createdAt: '2024-01-01',
    updatedAt: '2024-09-25',
    level: 0
  };

  const teamNames = ['前端团队', '后端团队', '算法团队'];

  // 2. 创建3个团队目标
  for (let t = 0; t < 3; t++) {
    const teamId = `TEAM-${String(t + 1).padStart(3, '0')}`;
    const teamKeyResults = generateKeyResults(teamId, 2);
    keyResults[teamId] = teamKeyResults;

    const teamProgress = Math.round(teamKeyResults.reduce((sum, kr) => sum + kr.progress, 0) / teamKeyResults.length);

    nodes[teamId] = {
      id: teamId,
      title: `${teamNames[t]}季度目标`,
      description: `${teamNames[t]}的季度发展目标和关键成果`,
      type: OKRNodeType.TEAM,
      parentId: deptId,
      children: [],
      keyResults: teamKeyResults,
      progress: teamProgress,
      status: teamProgress >= 100 ? OKRStatus.COMPLETED :
        teamProgress >= 75 ? OKRStatus.IN_PROGRESS : OKRStatus.NOT_STARTED,
      owner: {
        id: `user-team-${t + 1}`,
        name: `${teamNames[t]}负责人`,
        avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=team${t + 1}`,
        department: `技术部-${teamNames[t]}`
      },
      quarter,
      startDate: '2024-01-01',
      endDate: '2024-12-31',
      createdAt: '2024-01-01',
      updatedAt: '2024-09-25',
      level: 1
    };

    // 添加到部门的子节点
    nodes[deptId].children.push(teamId);

    // 3. 每个团队创建2个小组
    for (let g = 0; g < 2; g++) {
      const groupId = `GROUP-${String(t + 1).padStart(3, '0')}-${String(g + 1).padStart(2, '0')}`;
      const groupKeyResults = generateKeyResults(groupId, 2);
      keyResults[groupId] = groupKeyResults;

      const groupProgress = Math.round(groupKeyResults.reduce((sum, kr) => sum + kr.progress, 0) / groupKeyResults.length);

      nodes[groupId] = {
        id: groupId,
        title: `${teamNames[t]}第${g + 1}小组目标`,
        description: `${teamNames[t]}第${g + 1}小组的具体执行目标`,
        type: OKRNodeType.TEAM, // 小组也用团队类型
        parentId: teamId,
        children: [],
        keyResults: groupKeyResults,
        progress: groupProgress,
        status: groupProgress >= 100 ? OKRStatus.COMPLETED :
          groupProgress >= 75 ? OKRStatus.IN_PROGRESS : OKRStatus.NOT_STARTED,
        owner: {
          id: `user-group-${t + 1}-${g + 1}`,
          name: `小组${g + 1}负责人`,
          avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=group${t + 1}${g + 1}`,
          department: `技术部-${teamNames[t]}-第${g + 1}小组`
        },
        quarter,
        startDate: '2024-01-01',
        endDate: '2024-12-31',
        createdAt: '2024-01-01',
        updatedAt: '2024-09-25',
        level: 2
      };

      // 添加到团队的子节点
      nodes[teamId].children.push(groupId);

      // 4. 每个小组创建3-5个人的目标
      const personCount = 3 + Math.floor(Math.random() * 3); // 3-5个人
      for (let p = 0; p < personCount; p++) {
        counter++;
        const personId = `PERSON-${String(t + 1).padStart(3, '0')}-${String(g + 1).padStart(2, '0')}-${String(p + 1).padStart(2, '0')}`;
        const personKeyResults = generateKeyResults(personId, 2);
        keyResults[personId] = personKeyResults;

        const personProgress = Math.round(personKeyResults.reduce((sum, kr) => sum + kr.progress, 0) / personKeyResults.length);

        const names = ['小明', '小红', '小刚', '小丽', '小强', '小美', '小华', '小伟', '小芳', '小军'];
        const name = names[counter % names.length];

        nodes[personId] = {
          id: personId,
          title: `${name}的个人目标`,
          description: `${name}在${teamNames[t]}第${g + 1}小组的个人发展目标`,
          type: OKRNodeType.INDIVIDUAL,
          parentId: groupId,
          children: [],
          keyResults: personKeyResults,
          progress: personProgress,
          status: personProgress >= 100 ? OKRStatus.COMPLETED :
            personProgress >= 75 ? OKRStatus.IN_PROGRESS : OKRStatus.NOT_STARTED,
          owner: {
            id: `user-person-${counter}`,
            name: name,
            avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=person${counter}`,
            department: `技术部-${teamNames[t]}-第${g + 1}小组`
          },
          quarter,
          startDate: '2024-01-01',
          endDate: '2024-12-31',
          createdAt: '2024-01-01',
          updatedAt: '2024-09-25',
          level: 3
        };

        // 添加到小组的子节点
        nodes[groupId].children.push(personId);
      }
    }
  }

  return { nodes, keyResults };
}

// 生成组织架构式 Mock 数据
const { nodes: generatedNodes, keyResults: generatedKeyResults } = generateOrganizationalOKRTree();

// Mock OKR 节点数据（保留原有小规模数据作为示例，但已改用生成数据）
/*
const mockOKRNodes: Record<string, OKRNode> = {
  'dept-001': {
    id: 'dept-001',
    title: '技术部门年度目标',
    description: '推动公司数字化转型，提升技术竞争力，实现业务增长目标',
    type: OKRNodeType.DEPARTMENT,
    parentId: undefined,
    children: ['team-001', 'team-002'],
    keyResults: mockKeyResults['dept-001'],
    progress: 83,
    status: OKRStatus.IN_PROGRESS,
    owner: {
      id: 'mgr-001',
      name: '张技术',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=manager1',
      department: '技术部'
    },
    quarter: '2024Q4',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    createdAt: '2024-01-01',
    updatedAt: '2024-09-25',
    level: 0
  },
  'team-001': {
    id: 'team-001',
    title: '前端团队开发目标',
    description: '提升前端开发效率和代码质量，按时交付高质量产品功能',
    type: OKRNodeType.TEAM,
    parentId: 'dept-001',
    children: ['user-001', 'user-002'],
    keyResults: mockKeyResults['team-001'],
    progress: 84,
    status: OKRStatus.IN_PROGRESS,
    owner: {
      id: 'lead-001',
      name: '李前端',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=frontend1',
      department: '技术部-前端团队'
    },
    quarter: '2024Q4',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    createdAt: '2024-01-01',
    updatedAt: '2024-09-25',
    level: 1
  },
  'team-002': {
    id: 'team-002',
    title: '销售团队业绩目标',
    description: '扩大市场份额，提升销售业绩，开发新客户资源',
    type: OKRNodeType.TEAM,
    parentId: 'dept-001',
    children: ['user-003', 'user-004'],
    keyResults: mockKeyResults['team-002'],
    progress: 72,
    status: OKRStatus.IN_PROGRESS,
    owner: {
      id: 'lead-002',
      name: '王销售',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=sales1',
      department: '销售部'
    },
    quarter: '2024Q4',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    createdAt: '2024-01-01',
    updatedAt: '2024-09-22',
    level: 1
  },
  'user-001': {
    id: 'user-001',
    title: '前端开发工程师个人目标',
    description: '提升React开发技能，优化前端性能，完成组件库建设',
    type: OKRNodeType.INDIVIDUAL,
    parentId: 'team-001',
    children: [],
    keyResults: mockKeyResults['user-001'],
    progress: 78,
    status: OKRStatus.IN_PROGRESS,
    owner: {
      id: 'dev-001',
      name: '小明',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=dev1',
      department: '技术部-前端团队'
    },
    quarter: '2024Q4',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    createdAt: '2024-01-01',
    updatedAt: '2024-09-25',
    level: 2
  },
  'user-002': {
    id: 'user-002',
    title: 'UI设计师个人目标',
    description: '提升设计质量，完成产品界面改版，建立设计规范',
    type: OKRNodeType.INDIVIDUAL,
    parentId: 'team-001',
    children: [],
    keyResults: mockKeyResults['user-002'],
    progress: 80,
    status: OKRStatus.IN_PROGRESS,
    owner: {
      id: 'des-001',
      name: '小红',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=designer1',
      department: '技术部-前端团队'
    },
    quarter: '2024Q4',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    createdAt: '2024-01-01',
    updatedAt: '2024-09-23',
    level: 2
  },
  'user-003': {
    id: 'user-003',
    title: '销售代表个人目标',
    description: '提升客户拜访效率，增加销售转化率，扩大客户基础',
    type: OKRNodeType.INDIVIDUAL,
    parentId: 'team-002',
    children: [],
    keyResults: mockKeyResults['user-003'],
    progress: 81,
    status: OKRStatus.IN_PROGRESS,
    owner: {
      id: 'sal-001',
      name: '小刚',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=sales2',
      department: '销售部'
    },
    quarter: '2024Q4',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    createdAt: '2024-01-01',
    updatedAt: '2024-09-21',
    level: 2
  },
  'user-004': {
    id: 'user-004',
    title: '区域销售经理个人目标',
    description: '拓展华南市场，建立渠道网络，提升区域销售业绩',
    type: OKRNodeType.INDIVIDUAL,
    parentId: 'team-002',
    children: [],
    keyResults: mockKeyResults['user-004'],
    progress: 60,
    status: OKRStatus.IN_PROGRESS,
    owner: {
      id: 'sal-002',
      name: '小李',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=sales3',
      department: '销售部'
    },
    quarter: '2024Q4',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    createdAt: '2024-01-01',
    updatedAt: '2024-09-17',
    level: 2
  }
};
*/

/**
 * Mock OKR API 类
 */
class MockOKRApi {
  private nodes = { ...generatedNodes }; // 使用生成的大规模数据
  private keyResults = { ...generatedKeyResults };

  /**
   * 获取指定季度的 OKR 树数据
   * @param quarter 季度 (如: "2024Q4")
   * @returns Promise<OKRApiResponse>
   */
  async getOKRTree(quarter: string): Promise<OKRApiResponse<{ nodes: Record<string, OKRNode>; rootNodes: string[] }>> {
    await delay(300); // 模拟网络延迟

    try {
      // 过滤指定季度的节点
      const filteredNodes = Object.values(this.nodes)
        .filter(node => node.quarter === quarter)
        .reduce((acc, node) => {
          acc[node.id] = node;
          return acc;
        }, {} as Record<string, OKRNode>);

      // 获取根节点列表
      const rootNodes = Object.values(filteredNodes)
        .filter(node => !node.parentId)
        .map(node => node.id);

      return {
        success: true,
        data: {
          nodes: filteredNodes,
          rootNodes
        },
        message: '获取 OKR 树数据成功'
      };
    } catch (error) {
      return {
        success: false,
        data: { nodes: {}, rootNodes: [] },
        message: '获取 OKR 树数据失败',
        code: 'FETCH_ERROR'
      };
    }
  }

  /**
   * 创建新的 OKR 节点
   * @param nodeData 节点数据
   * @returns Promise<OKRApiResponse<OKRNode>>
   */
  async createOKRNode(nodeData: CreateOKRNodeRequest): Promise<OKRApiResponse<OKRNode>> {
    await delay(500); // 模拟网络延迟

    try {
      const nodeId = generateId();
      const now = new Date().toISOString();

      // 计算节点层级
      let level = 0;
      if (nodeData.parentId) {
        const parentNode = this.nodes[nodeData.parentId];
        if (parentNode) {
          level = parentNode.level + 1;
        }
      }

      // 创建关键结果
      const keyResults: KeyResult[] = nodeData.keyResults?.map(kr => ({
        ...kr,
        id: generateId(),
        createdAt: now,
        updatedAt: now
      })) || [];

      // 计算整体进度
      const progress = keyResults.length > 0
        ? Math.round(keyResults.reduce((sum, kr) => sum + kr.progress, 0) / keyResults.length)
        : 0;

      const newNode: OKRNode = {
        id: nodeId,
        title: nodeData.title,
        description: nodeData.description,
        type: nodeData.type,
        parentId: nodeData.parentId,
        children: [],
        keyResults,
        progress,
        status: OKRStatus.NOT_STARTED,
        owner: {
          id: nodeData.ownerId,
          name: '新用户', // 在实际应用中应该从用户数据中获取
          avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${nodeData.ownerId}`,
          department: nodeData.type === OKRNodeType.DEPARTMENT ? nodeData.title : '未知部门'
        },
        quarter: nodeData.quarter,
        startDate: nodeData.startDate,
        endDate: nodeData.endDate,
        createdAt: now,
        updatedAt: now,
        level
      };

      // 保存节点
      this.nodes[nodeId] = newNode;
      this.keyResults[nodeId] = keyResults;

      return {
        success: true,
        data: newNode,
        message: '创建 OKR 节点成功'
      };
    } catch (error) {
      return {
        success: false,
        data: {} as OKRNode,
        message: '创建 OKR 节点失败',
        code: 'CREATE_ERROR'
      };
    }
  }

  /**
   * 更新 OKR 节点
   * @param nodeId 节点ID
   * @param data 更新的数据
   * @returns Promise<OKRApiResponse<OKRNode>>
   */
  async updateOKRNode(nodeId: string, data: Partial<OKRNode>): Promise<OKRApiResponse<OKRNode>> {
    await delay(300);

    try {
      const existingNode = this.nodes[nodeId];
      if (!existingNode) {
        return {
          success: false,
          data: {} as OKRNode,
          message: '节点不存在',
          code: 'NODE_NOT_FOUND'
        };
      }

      const updatedNode = {
        ...existingNode,
        ...data,
        id: nodeId, // 确保ID不被覆盖
        updatedAt: new Date().toISOString()
      };

      this.nodes[nodeId] = updatedNode;

      return {
        success: true,
        data: updatedNode,
        message: '更新 OKR 节点成功'
      };
    } catch (error) {
      return {
        success: false,
        data: {} as OKRNode,
        message: '更新 OKR 节点失败',
        code: 'UPDATE_ERROR'
      };
    }
  }

  /**
   * 删除 OKR 节点
   * @param nodeId 节点ID
   * @returns Promise<OKRApiResponse<string>>
   */
  async deleteOKRNode(nodeId: string): Promise<OKRApiResponse<string>> {
    await delay(200);

    try {
      const node = this.nodes[nodeId];
      if (!node) {
        return {
          success: false,
          data: '',
          message: '节点不存在',
          code: 'NODE_NOT_FOUND'
        };
      }

      // 递归删除所有子节点
      const deleteRecursively = (id: string) => {
        const nodeToDelete = this.nodes[id];
        if (nodeToDelete) {
          nodeToDelete.children.forEach(childId => {
            deleteRecursively(childId);
          });
          delete this.nodes[id];
          delete this.keyResults[id];
        }
      };

      deleteRecursively(nodeId);

      return {
        success: true,
        data: nodeId,
        message: '删除 OKR 节点成功'
      };
    } catch (error) {
      return {
        success: false,
        data: '',
        message: '删除 OKR 节点失败',
        code: 'DELETE_ERROR'
      };
    }
  }

  /**
   * 更新关键结果进度
   * @param updateData 更新数据
   * @returns Promise<OKRApiResponse>
   */
  async updateKeyResult(updateData: UpdateKeyResultRequest): Promise<OKRApiResponse<{ nodeId: string; keyResult: KeyResult }>> {
    await delay(200);

    try {
      const { nodeId, keyResultId, currentValue, status } = updateData;
      const node = this.nodes[nodeId];

      if (!node) {
        return {
          success: false,
          data: { nodeId: '', keyResult: {} as KeyResult },
          message: '节点不存在',
          code: 'NODE_NOT_FOUND'
        };
      }

      const keyResultIndex = node.keyResults.findIndex(kr => kr.id === keyResultId);
      if (keyResultIndex === -1) {
        return {
          success: false,
          data: { nodeId: '', keyResult: {} as KeyResult },
          message: '关键结果不存在',
          code: 'KEY_RESULT_NOT_FOUND'
        };
      }

      const keyResult = node.keyResults[keyResultIndex];

      // 计算新的进度
      const progress = Math.min(100, Math.round((currentValue / keyResult.targetValue) * 100));

      // 更新关键结果
      const updatedKeyResult: KeyResult = {
        ...keyResult,
        currentValue,
        progress,
        status: status || (progress >= 100 ? OKRStatus.COMPLETED : OKRStatus.IN_PROGRESS),
        updatedAt: new Date().toISOString()
      };

      node.keyResults[keyResultIndex] = updatedKeyResult;
      this.keyResults[nodeId][keyResultIndex] = updatedKeyResult;

      // 重新计算节点整体进度
      const totalProgress = node.keyResults.reduce((sum, kr) => sum + kr.progress, 0);
      node.progress = Math.round(totalProgress / node.keyResults.length);
      node.updatedAt = new Date().toISOString();

      return {
        success: true,
        data: {
          nodeId,
          keyResult: updatedKeyResult
        },
        message: '更新关键结果成功'
      };
    } catch (error) {
      return {
        success: false,
        data: { nodeId: '', keyResult: {} as KeyResult },
        message: '更新关键结果失败',
        code: 'UPDATE_KEY_RESULT_ERROR'
      };
    }
  }
}

// 导出单例实例
export const mockOKRApi = new MockOKRApi();
